package com.tgy.JUC.VolatileDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/***
 * @ClassName: Atomicity
 * @Description: 测试不保证原子性
 * @Auther: 送你一块二向箔
 * @Date: 15:46 2022/3/15
 * @version : V1.0
 */
public class Atomicity {
    private volatile static int sum =0;//加了结果还是不对，不保证原子性
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public static Lock lock = readWriteLock.writeLock();

    public static void main(String[] args) {
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 1000; i1++) {
                    addLock();
                }
            }).start();
        }


        while(Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+"  sum =====>"+sum);
    }

    public static void add(){
        sum++;//不是一个原子操作
    }

    public synchronized static void addSync(){
        sum++;
    }

    public static void addLock(){

        lock.lock();
        try {
            sum++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
